import { refreshToken as refreshTokenApi } from "@/api/login"

// 刷新token
setInterval(async () => {
  const storage = JSON.parse(localStorage.getItem("refreshInfo") as any) || {}
  if (Object.keys(storage).length === 0) return
  const currentTime = new Date().getTime()
  const diff = storage.expiresTime - currentTime
  // 距离token过期时间10分钟内刷新token
  if (diff > 0 && diff < 600000) {
    if (!storage.refreshToken) return
    const resp = await refreshTokenApi()
    const { token, expiresTime, refreshToken } = resp
    localStorage.setItem("token", token)
    localStorage.setItem("refreshInfo", JSON.stringify({ refreshToken, expiresTime }))
  }
}, 60000)

// 处理加载报错：https://cn.vitejs.dev/guide/build#load-error-handling
window.addEventListener('vite:preloadError', () => {
  window.location.reload()
})